JS30 Day 22 筆記


Posted by GL on 2023-05-23

功能

利用getBoundingClientRect 讓 highlight 的樣式跟著滑鼠指定的位置移動

Demo

step 1 : 取得 HTML 頁面中的元素

拿到所有的 a 元素, 並創建一個 highlight 的 span 元素

// 選取所有的 a 元素
const triggers = document.querySelectorAll('a')

// 建立一個 span, class 名稱為 highlight,來產生 highlight 樣式
const highlight = document.createElement('span')
highlight.classList.add('highlight')

// 將 span 放在在 body
document.body.appendChild(highlight)

step 2 : 對所有 a 元素監聽滑鼠移入事件,並觸發 highlightLink function

mouseenter:當滑鼠移到 target 時驅動。

function highlightLink(){
  console.log(this);
}
triggers.forEach(a => a.addEventListener('mouseenter', highlightLink));

step 3 : 取得 a 元素的位置, 再讓 highlight 樣式位置根據 a 元素做調整

function highlightLink() {
  // this 為 mouseenter 事件當前觸發的元素
  const linkCoords = this.getBoundingClientRect();

  // 建立 coords 物件來儲存 a 元素寬高、在視窗中位置的資訊
  // 爲了校正視窗卷軸 scrooll 後的位移, 在 top、left 中加上 window.scrollY 以及 window.scrollX
  const cords = {
    width: linkCoords.width,
    height: linkCoords.height,
    left: linkCoords.left + window.scrollX,
    top: linkCoords.top + window.scrollY
  }
  // 根據 cords 物件,調整 highlight 樣式的寬高及位置
  highlight.style.width = `${cords.width}px`;
  highlight.style.height = `${cords.height}px`;

// translate(x, y):從原本定位移動 x,y 距離。
  highlight.style.transform = `translate(${cords.left}px, ${cords.top}px`;
}

完整程式碼

const triggers = document.querySelectorAll('a');
const highlight = document.createElement('span');
highlight.classList.add('highlight');
document.body.appendChild(highlight);

function highlightLink(){
  const linkCoords = this.getBoundingClientRect();
  const coords = {
    width : linkCoords.width,
    height : linkCoords.height,
    top : linkCoords.top + window.scrollY,
    left : linkCoords.left + window.scrollX
  };

  highlight.style.width = `${coords.width}px`;
  highlight.style.height = `${coords.height}px`;
  highlight.style.transform = `translate(${coords.left}px, ${coords.top}px)`;
}

triggers.forEach(a => a.addEventListener('mouseover', highlightLink));

參考資料:


#JS 30







Related Posts

Day 45 - Beautiful Soup & Web scraping & robots.txt

Day 45 - Beautiful Soup & Web scraping & robots.txt

Git 常忘指令

Git 常忘指令

學習 Git (6) - 修改 commit 紀錄 part 1:commit 參數 --amend

學習 Git (6) - 修改 commit 紀錄 part 1:commit 參數 --amend


Comments